use miniLanDrop::{
    core::{
        cli::cli_monitor,
        protocol::{detector::start_discovery_service, transfer::start_transfer_service},
    },
    get_config, CONFIG,
};
use miniLanDrop::core::DeviceInfo;
use log::{info, error, warn};
use log4rs;
use std::{
    collections::HashMap,
    net::{IpAddr, Ipv4Addr},
    sync::Arc,
};
use tokio::sync::{Mutex, mpsc};
use miniLanDrop::core::process::process;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    log4rs::init_file("log4rs.yaml", Default::default()).unwrap();
    get_config();
    info!("欢迎使用 miniLanDrop 文件传输服务!");
    info!("请确保在同一局域网内运行此服务。");
    let device_name = CONFIG.get().unwrap().info.device_name.clone();
    let address = CONFIG.get().unwrap().address.clone();
    let device_name = match device_name.is_empty() {
        true => {
            warn!("设备名称未设置(使用随机名称)。请在命令行参数中设置 name 或通过环境变量 DEVICE_NAME 设置。");
            format!("Device-{}", rand::random::<u16>())
        }
        false => device_name,
    };
    // 共享设备列表
    let devices: Arc<Mutex<HashMap<u64, DeviceInfo>>> = Arc::new(Mutex::new(HashMap::new()));
    let (tx, rx) = mpsc::channel(32);
    // 启动设备发现服务
    let discovery =
        start_discovery_service(device_name.clone(), devices.clone(), tx.clone()).await?;
    // 启动文件传输服务
    let transfer = start_transfer_service(address.transfer_port, tx.clone()).await?;
    info!(
        "{} 已启动 | IP: {} | 监听端口: {} | 传输端口: {}",
        device_name,
        get_local_ip().unwrap_or(IpAddr::V4(Ipv4Addr::LOCALHOST)),
        CONFIG.get().unwrap().address.listen_port,
        address.transfer_port,
    );
    tokio::spawn(async move {
        if let Err(e) = cli_monitor(tx.clone()).await {
            error!("命令行监控错误: {}", e);
        }
    });
    process(devices,rx).await;
    // 保持服务运行
    discovery.handle.await??;
    transfer.handle.await?;
    Ok(())
}

// 获取本地IP地址
fn get_local_ip() -> Option<IpAddr> {
    local_ip_address::local_ip().ok()
}
